package cn.edu.cqu.services.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.domains.StudyNews;
import cn.edu.cqu.services.StudyNewsCRUD;

@Service("StudyNewsCRUDHibernate")
public class StudyNewsCRUDHibernate implements StudyNewsCRUD {

	
	private HibernateTemplate ht;
	private Session session;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
		session = ht.getSessionFactory().openSession();
	}
	
	@Override
	public StudyNews getByID(String sID) {
		return ht.get(StudyNews.class, sID);
	}

	@Override
	@Transactional
	public StudyNews edit(StudyNews studyNews) {
		return ht.merge(studyNews);
	}

	@Override
	@Transactional
	public void deleteByID(String sID) {
		StudyNews studyNews = this.getByID(sID);
		ht.delete(studyNews);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<StudyNews> getSubAll(int subType, int pageNo, int pageSize) {
		String hql = "from StudyNews where sNewsType=?  order by sNewsDate desc";
		Query query = session.createQuery(hql);
		query.setInteger(0, subType);
		return query.setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<StudyNews> getAll(int pageNo, int pageSize) {
		String hql = "from StudyNews  order by sNewsDate desc";
		Query query = session.createQuery(hql);
		return query.setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list();
	}

}
